package com.neuedu.corejava.ch13.homework;


/**
 * 20190815
 * 没有线程同步的示例：
 * 可能多个线程对同一个资源进行访问，可能造成数据共享的安全
 * @author admin
 *
 */
public class HomeWork2 {
	
private int count=0;
	
	public void add(int threadId){
		count++;
		System.out.println(threadId+","+count);
	}
	
	public void desc(int threadId){
		count--;
		System.out.println(threadId+","+count);
	}
	
	class AddClass implements Runnable{
		private int threadId=0;
		private AddClass(int id){
			this.threadId=id;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			for(int i=0;i<50;i++){
				add(threadId);
				
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		
	}
	
	class DescClass implements Runnable{
		private int threadId=0;
		private DescClass(int id){
			this.threadId=id;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			for(int i=0;i<50;i++){
				desc(threadId);
				
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		
	}
	
	public static void main(String[] args) {
		HomeWork2 homeWork2=new HomeWork2();
		AddClass addClass1=homeWork2.new AddClass(1);
		AddClass addClass2=homeWork2.new AddClass(2);
		
		DescClass descClass1=homeWork2.new DescClass(3);
		DescClass descClass2=homeWork2.new DescClass(4);
		
		new Thread(addClass1).start();
		new Thread(addClass2).start();
		new Thread(descClass1).start();
		new Thread(descClass2).start();
		
		
	}
	

}
